import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { uniAdapter } from 'uni-axios-adapter';

interface ApiResponse<T = any> {
  code: number;
  data: T;
  msg: string;
}

const request = axios.create({
  baseURL: 'http://localhost:3000/',
  timeout: 5000,
  adapter: uniAdapter, // 使用 uni-app 适配器
});
// 请求拦截器
request.interceptors.request.use(
  (config:AxiosRequestConfig) => {
    // 添加 token（从本地存储获取）
    const token = uni.getStorageSync('token');
    if (token) {
      config.headers = config.headers || {};
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const { code, data, message } = response.data;
    if (code === 200) {
      return data; // 成功返回数据
    } else {
      uni.showToast({ title: message || '请求失败', icon: 'none' });
      return Promise.reject(new Error(message));
    }
  },
  (error) => {
    // 处理 HTTP 错误
    if (error.response) {
      const { status } = error.response;
      switch (status) {
        case 401:
          uni.showToast({ title: '未授权，请登录', icon: 'none' });
          uni.navigateTo({ url: 'src/pages/login/index' });
          break;
        case 403:
          uni.showToast({ title: '无权限访问', icon: 'none' });
          break;
        case 500:
          uni.showToast({ title: '服务器错误', icon: 'none' });
          break;
        default:
          uni.showToast({ title: '网络错误', icon: 'none' });
      }
    } else {
      uni.showToast({ title: '网络连接失败', icon: 'none' });
    }
    return Promise.reject(error);
  }
);

// 封装 GET、POST 方法
export const get = <T = any>(url: string, params?: any): Promise<T> => {
  return request.get(url, { params });
};

export const post = <T = any>(url: string, data?: any): Promise<T> => {
  return request.post(url, data);
};

export default request;